package com.xiaoq.push.service;

import java.util.List;


import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.push.entity.MessageEntity;
import com.xiaoq.push.entity.MsgCatalogueEntity;

@Service
public class MsgCatalogueService {
	
	@Autowired
	private IdGenerator idGenerator;

	private static final Logger LOG = LoggerFactory.getLogger(MsgCatalogueService.class);

	@Autowired
	private Datastore datastore;

	@Autowired
	private PushMessageService pushMessageService;

	/**
	 * 在本地保存一条消息目录
	 * @param msgCatalogueEntity
	 */
	public void createMsgCatalogue(MsgCatalogueEntity msgCatalogueEntity) {
		msgCatalogueEntity.setId(idGenerator.nextId());
		datastore.save(msgCatalogueEntity);
	}
	
	/**
	 * 消息在本地数据库里面是存一份的但是这样去怎么具有实时性呢
	 * @param userId
	 * @return
	 */
	public List<MsgCatalogueEntity> getMsgCatalogues(String userId) {
		LOG.info("userId:" + userId);
		Query<MsgCatalogueEntity> msgcatalogueQuery = datastore.find(MsgCatalogueEntity.class);
		List<MsgCatalogueEntity> msgCatalogueList = msgcatalogueQuery.asList();
		for (MsgCatalogueEntity msgcatalogue : msgCatalogueList) {
			LOG.info(" msgCatalogueCode = " + msgcatalogue.getMsgCatalogueCode());
			MessageEntity msgEntity = pushMessageService.findLastMessageOfUserByMsgCatalogueCode(userId,
					msgcatalogue.getMsgCatalogueCode());
			if (msgEntity != null) {
				msgcatalogue.setTitleOfLastMsg(msgEntity.getMsgTitle());
				msgcatalogue.setReceivedTimeOfLastMsg(msgEntity.getCreatedAt());
			}

		}
		return msgCatalogueList;

	}
	
	public MsgCatalogueEntity getMsgCatalogue(String catalogueCode){

		return datastore.find(MsgCatalogueEntity.class).field("msgCatalogueCode").equal(catalogueCode).get();
		
	}

}
